<?php
// +----------------------------------------------------------------------
// | likeshop100%开源免费商用商城系统
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | 商业版本务必购买商业授权，以免引起法律纠纷
// | 禁止对系统程序代码以任何目的，任何形式的再发布
// | gitee下载：https://gitee.com/likeshop_gitee
// | github下载：https://github.com/likeshop-github
// | 访问官网：https://www.likeshop.cn
// | 访问社区：https://home.likeshop.cn
// | 访问手册：http://doc.likeshop.cn
// | 微信公众号：likeshop技术社区
// | likeshop团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeshopTeam
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\http\middleware;


use app\common\cache\UserTokenCache;
use app\common\service\JsonService;
use app\api\service\UserTokenService;
use app\api\service\WechatUserService;
use app\common\enum\user\UserTerminalEnum;
use think\facade\Config;
use think\facade\Log;

class WxCloudMiddleware
{
    /**
     * @notes 微信中间件
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     * @author 令狐冲
     * @date 2021/7/1 17:33
     */
    public function handle($request, \Closure $next)
    {
        /**
         * 
            // HTTP_X_WX_SOURCE	other
            // HTTP_X_WX_SERVICE	thinkphp-nginx-y8us
            // HTTP_X_WX_PLATFORM	devtools
            // HTTP_X_WX_OPENID	okeT2678dZv_bVQ8QVmqqwYitHtc
            // HTTP_X_WX_ENV	prod-0gdpyz637d16cecb
            // HTTP_X_WX_CALL_ID	0.002371018877854958_1737205101878
            // HTTP_X_WX_APPID	wxb2060950af16c3eb
            // HTTP_X_CLOUDBASE_VERSION	thinkphp-nginx-y8us-008
            // HTTP_X_CLOUDBASE_TRACE	YzBiNDUxZDNiODJmNDFiZDliOTI4ZDNlZTIwODc5YzIsYzQzZjE4NDc0NjgwNGYyZTlmNTFmNmI1ODYzMWJlMWQsb24=
            // HTTP_X_CLOUDBASE_TIMESTAMP_MS	1737205103723
            // HTTP_X_CLOUDBASE_TIMESTAMP	1737205103
            // HTTP_X_CLOUDBASE_SESSIONTOKEN	wmyrB1UA4exrWKjSn33SH4vy4U0Opina655b9cb8cd548146aaf2999cc0ac08e21EJvlI69ZWKeVCn2aMg1FOBR1-Q7SUsJuOv7jGkDfWJ3_WdxKaKz4L65YuYxKj6QdgSeAcbZxl5oKcn8ls_PWMybaoAijyGDOcV5igZJz2Z6YxlITCd6kTtoVtCb8xXhbjQenyG3r7FR4QdZm8HsKK_m-aPn40A1QPyyMBNE9bIz8oJeZYDYay3tTEU9XkB-V2vbhEtefunCNzWW7f7GTp_m9sQ2UtoNu4ZObJHFQ7Co93RD2hqj07MDshqSfo70zNvoAo0iyCIF_8b43sfN5XHJ0X2s9m9YsO__XjkyxL3hkHeA4IwzeRuxO-sXncxHVogClujCHOTBS9CG_W3GGkSJpnjijFVZv1knqfek0Db6TggylpWQkFBPAjSEcJIa
            // HTTP_X_CLOUDBASE_REQUEST_ID	e698409d-d59b-11ef-9215-525400f741c5
            // HTTP_X_CLOUDBASE_CONTEXT	H4sIAAAAAAAA/4yPP2+DMBBHv8vNoTobsB3WLu1SKVKF1C4I7GuwQmwHzJ80ynevYOlSVVmf3j3d7wbkplcDBYTemwSPJly/RSoNE5p0AzsYrYMCGCJmmGUCOV/hQP125U/0zoVU5nOqmvKgDuX5cpk/bHyJGnYwUD9ZTW/1maCA2Fp3Cm1I3NG6Jbmqcfh1SuoH693fWoKoVtWPvV5L81IZmqL33VqYSbd1fPYu0hKhuIGuu257D58QeSoZMqWkVHm2z1XFZCo55iuU/1R9IPfIxjqETZuXhqPAfY71FxM6pQbu958AAAD//7R5md1gAQAA
            // HTTP_X_CLOUDBASE_AUTHORIZATION	1.0.0 TC3-HMAC-SHA256 Credential=AKIDORXjtP5BzGxP1zgYJNiwi7Krqq2Hrj-_zeb5gKc--PnNpcxT6TJ9pLPrLtPZqq21/2025-01-18/tcb/tc3_request, SignedHeaders=content-type;host, Signature=3e810cf42470187567cf2b8d7069849a7d464ab10c9f49df3e88a1e4dc53342f
            // HTTP_VERSION	1.1.3
            // HTTP_REFERER	https://servicewechat.com/wxb2060950af16c3eb/devtools/page-frame.html
            // HTTP_FORWARDED	for=223.102.69.172; host=thinkphp-nginx-y8us-prod-0gdpyz637d16cecb-1336975851.ap-shanghai.run.wxcloudrun.com
            // HTTP_CONTENT_TYPE	application/json
            // HTTP_ACCEPT_ENCODING	deflate, gzip
            // HTTP_USER_AGENT	Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1 wechatdevtools/1.06.2409140 MicroMessenger/8.0.5 Language/zh_CN webview/
            // HTTP_CONTENT_LENGTH	14
            // HTTP_X_ORIGINAL_FORWARDED_FOR	223.102.69.172
            // HTTP_X_SCHEME	http
            // HTTP_X_FORWARDED_PROTO	http
            // HTTP_X_FORWARDED_PORT	80
            // HTTP_X_FORWARDED_HOST	thinkphp-nginx-y8us-prod-0gdpyz637d16cecb-1336975851.ap-shanghai.run.wxcloudrun.com
            // HTTP_X_FORWARDED_FOR	11.163.0.84
            // HTTP_X_REAL_IP	11.163.0.84
            // HTTP_X_REQUEST_ID	e698409d-d59b-11ef-9215-525400f741c5

            // HTTP_X_WX_OPENID
            // HTTP_X_WX_PLATFORM
            // HTTP_VERSION
            // HTTP_X_ORIGINAL_FORWARDED_FOR
         */

        $token = $request->header('x-wx-openid');
        if(empty($token)){
            return JsonService::fail('请求参数缺token', [], 0, 0);
        }
        // $ip = $request->header('HTTP_X_ORIGINAL_FORWARDED_FOR');
        // $request->header('HTTP_X_WX_OPENID', $ip);
        //判断接口是否免登录
        $userInfo = (new UserTokenCache())->getUserInfo($token);

        if (empty($userInfo)) {
            //token过期无效并且该地址需要登录才能访问
            $userServer = new WechatUserService(['openid'=>$token], UserTerminalEnum::WECHAT_MMP);
            $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo(true,false);
            $userInfo['expire_time'] = time();
        }


        //token临近过期，自动续期
        if ($userInfo) {
            //获取临近过期自动续期时长
            $beExpireDuration = Config::get('project.user_token.be_expire_duration');

            //token续期
            if (time() > ($userInfo['expire_time'] - $beExpireDuration)) {

                $result = UserTokenService::overtimeToken($token);

                //续期失败（数据表被删除导致）
                if (empty($result)) {
                    return JsonService::fail('登录过期', [], -1);
                }

            }
        }
        //给request赋值，用于控制器
        $request->userInfo = $userInfo;
        $request->userId = $userInfo['user_id'] ?? 0;

        return $next($request);
    }

}